<?php
declare(strict_types=1);
namespace app\index\controller;
use aphp\core\Jump;

class User
{
    use Jump;
    protected array $middleware = [
        'auth' => ['except' => ['captcha','login','logout','register', 'info']], // 除外
    ];

    public function info(string $id)
    {
        $vo = db('user')->where('id', $id)->find();
        if (!$vo) {
            $this->error('用户不存在');
        }
        return view()->with('vo', $vo);
    }

    // 验证码图片
    public function captcha()
    {
        return extend('captcha')->make();
    }

    // 登录
    public function login(array $req)
    {
        if ($this->isPost()) {
            $model = model('common.user');
            $r = $model->login($req);
            $this->_jump(['登录成功', $model->getError()], $r, 'index/index');
        }
        return view();
    }

    // 退出
    public function logout()
    {
        session(null);
        $this->success('退出成功', 'user/login');
    }

    // 注册
    public function register(array $req)
    {
        if ($this->isPost()) {
            $r = model('common.user')->save($req);
            $this->_jump(['注册成功', '注册失败'], $r, 'user/login?from=' . $req['username']);
        }
        return view();
    }

    // 个人中心
    public function index()
    {
        $uid = session('user.id');
        $user = model('common.user')->find($uid);
        $vo = $user->toArray();
        return view()->with(['vo' => $vo]);
    }

    // 修改资料
    public function profile(array $req)
    {
        $uid = session('user.id');
        $user = model('common.user')->find($uid);
        if ($this->isPost()) {
            $r = $user->save($req);
            $this->_jump(['修改成功', '修改失败'], $r, 'index');
        }
        return view()->with('vo', $user->toArray());
    }

    // 修改密码
    public function password(array $req)
    {
        if ($this->isPost()) {
            $user = model('common.user');
            $r = $user->changePwd($req);
            $this->_jump(['修改成功', $user->getError()], $r, 'index');
        }
        return view();
    }

    // 获取用户可管理的文集ID
    protected function _member_book_id(): array
    {
        $uid = session('user.id');
        return db('book')->where('user_id', $uid)->order('id ASC')->cache()->column('id');
    }

    // 成员管理
    public function member()
    {
        $book_ids = $this->_member_book_id();
        if (empty($book_ids)) {
            $book_ids = [0];
        }
        $list = db('book_member')->where('book_id', 'in', $book_ids)->where('role_level<3')->order('status ASC,id DESC')->paginate(10);
        return view()->with(['list' => $list]);
    }

    // 成员审核
    public function member_state(string $ids, string $params)
    {
        $ids = ids_filter($ids, true);
        if (empty($ids)) {
            $this->error('请选择ID');
        }
        [$field, $value] = split_prefix_name($params, 'status', '-');
        $map = [];
        $map[] = [$field, '<>', $value];
        if (count($ids) == 1) {
            $map['id'] = current($ids);
        } else {
            $map[] = ['id', 'in', $ids];
        }
        $map[] = ['book_id', 'in', $this->_member_book_id()]; // 加入限制
        $title = ($value == 1) ? '通过审核' : '设为待审';
        $model = db('book_member');
        $r = $model->where($map)->setField($field, $value);
        if ($r) {
            cache_clear();
            cli('clear:runtime index common');
        }
        $this->_jump([$title . '成功', $title . '失败'], $r, 'user/member');
    }

    // 切换角色
    public function member_change(int $id)
    {
        $map = [];
        $map['id'] = $id;
        $map[] = ['book_id', 'in', $this->_member_book_id()]; // 加入限制
        $r = db('book_member')->where($map)->where('role_level=1')->setField('role_level', 2);
        if (!$r) {
            $r = db('book_member')->where($map)->where('role_level=2')->setField('role_level', 1);
        }
        if ($r) {
            cache_clear();
            cli('clear:runtime index common');
        }
        $this->_jump(['切换成功', '切换失败'], $r, 'user/member');
    }

    // viewer升级为editor
    public function member_upgrade(int $id)
    {
        $map = [];
        $map['id'] = $id;
        $map[] = ['book_id', 'in', $this->_member_book_id()]; // 加入限制
        $r = db('book_member')->where($map)->where('is_upgrade=1 AND role_level=1 AND status=1')->update(['is_upgrade'=> 2,'role_level'=>2]);
        if ($r) {
            cache_clear();
            cli('clear:runtime index common');
        }
        $this->_jump(['升级成功', '升级失败'], $r, 'user/member');
    }

    // 成员删除
    public function member_del(string $ids)
    {
        $ids = ids_filter($ids, true);
        if (!$ids) {
            $this->error('请选择ID');
        }
        $map = [];
        $map[] = ['book_id', 'in', $this->_member_book_id()]; // 加入限制
        $map[] = ['role_level', '<', 3];
        $map['status'] = 0;
        $model = model('common.book_member');
        $count = 0; // 成功删除数量
        foreach ($ids as $id) {
            $tmp = $model->where($map)->find($id);
            if ($tmp) {
                $ok = pdo()->trans(function () use ($tmp) {
                    $tmp->del();
                });
                if ($ok) $count++;
            }
        }
        if ($count > 0) {
            cache_clear();
            cli('clear:runtime index common');
        }
        $this->_jump(['删除成功', '删除失败，先要设为待审'], $count, 'user/member');
    }
}